<template>
  <div class="cmt-container">
    <h3>发表评论</h3>
    <hr>
    <textarea placeholder="请输入要bb的内容(最多120字)"
              maxlength="120"
              v-model="msg"></textarea>
    <mt-button type="primary"
               size="large"
               @click="postComment">发表评论</mt-button>
    <div class="cmt-list">
      <div class="cmt-item"
           v-for="(item, index) in comments"
           :key="index">
        <div class="cmt-title">
          第{{index + 1}}楼&nbsp;&nbsp;用户：{{item.username}}&nbsp;&nbsp;发表时间：{{item.add_time | dateFormat}}
        </div>
        <div class="cmt-body">
          {{item.content}}
        </div>
      </div>
    </div>
    <mt-button type="danger"
               size="large"
               plain
               @click="getMore">加载更多</mt-button>
  </div>
</template>

<script>
import { Toast } from 'mint-ui';
export default {
  data() {
    return {
      page: 1,
      comments: [],
      msg: ''
    }
  },
  created() {
    this.getComments()
  },
  methods: {
    getComments() {
      this.axios(`/getcomments?_id=${this.id}&_page=${this.page}&_limit=2`).then(res => {
        if (res.status == 200) {
          if (!res.data.length && this.page != 1) Toast('没有更多评论了');
          this.comments = this.comments.concat(res.data);
        } else {
          Toast('加载评论失败')
        }
      })
    },
    getMore() {
      this.page++;
      this.getComments();
    },
    postComment() {
      if (this.msg.trim().length == 0) return Toast('评论内容不能为空');
      let cmt = { _id: this.id, username: '匿名用户', add_time: new Date(), content: this.msg.trim() };
      this.comments.unshift(cmt);
      this.msg = '';
      this.axios.post('/getcomments', cmt).then(res => {
        Toast('发表成功');
      })
    }
  },
  props: ['id']
}
</script>

<style lang="scss" scoped>
.cmt-container {
  h3 {
    font-size: 18px;
  }
  textarea {
    font-size: 14px;
    height: 85px;
    margin-bottom: 0;
  }
  .cmt-list {
    margin: 5px 0;
    .cmt-item {
      font-size: 13px;
      .cmt-title {
        line-height: 30px;
        background-color: #eee;
      }
      .cmt-body {
        text-indent: 2em;
        line-height: 35px;
      }
    }
  }
}
</style>